package com.sense.kukoo.biz_me.view

import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.sense.feel.common.utils.ToastUtils
import com.sense.kukoo.biz_me.R
import com.sense.kukoo.biz_me.databinding.BizMeActivityProfileBinding
import com.sense.kukoo.biz_me.vm.ProfileViewModel
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.common.event.UserEditEvent
import com.sense.kukoo.common.file.FileConfig
import com.sense.kukoo.common.mvvm.view.BaseMvvmActivity
import com.sense.kukoo.common.repo.Repo
import com.sense.kukoo.common.utils.ApplicationContext
import com.sense.kukoo.lib_logger.LoggerManager
import com.sense.kukoo.lib_picture.config.GlideConfig
import com.sense.kukoo.lib_picture.loader.Monet
import com.yalantis.ucrop.UCrop
import org.greenrobot.eventbus.EventBus
import java.io.File


@Route(path = ARouterUrl.ROUTE_ME_MODULE_PROFILE_ACTIVITY)
class ProfileActivity : BaseMvvmActivity<ProfileViewModel, BizMeActivityProfileBinding>() {

    private val TAG: String = javaClass.simpleName

    override fun getLayoutId(): Int = R.layout.biz_me_activity_profile

    override fun getViewModelClass(): Class<ProfileViewModel> = ProfileViewModel::class.java

    override fun responseVM(action: Int) {}

    companion object{
        val CODE_GET_PHOTO = 101
    }

    override fun initData() {
        mBinding.lifecycleOwner = this
        mBinding.vm = mViewModel
        mBinding.titleView.init(this)
        setSupportActionBar(mBinding.titleView)
    }

    override fun initView() {
        mBinding.ivIcon.setOnClickListener {
            getPhoto()
        }
        mBinding.tvBtnSave.setOnClickListener{
            mViewModel.setSaveUserInfo()
        }
        mBinding.etNewUserName.addTextChangedListener(object :TextWatcher{

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}

            override fun afterTextChanged(s: Editable?) {
                mViewModel.checkSaveBtnEnable()
            }
        })
        bindAction(mViewModel.action_editSuccess){
            EventBus.getDefault().post(UserEditEvent())
            finish()
        }
        //
        mViewModel.initData()
        //
        val avatarUrl:String? = Repo.user.get()?.avatarUrl
        avatarUrl?.let {
            Monet.get(ApplicationContext.instance())
                .load<GlideConfig>(it)
                .placeholder(com.sense.kukoo.common_design.R.drawable.design_icon_avatar_default)
                .circleCrop()
                .into(mBinding.ivIcon)
        }
    }

    fun getPhoto(){
        val intent = Intent(Intent.ACTION_PICK)
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
        startActivityForResult(intent, CODE_GET_PHOTO)
    }

    fun cropPhoto(data: Intent?){
        data?.let {
            val cropFile = File(FileConfig.getImgDir()!!, "head_${System.currentTimeMillis()}.jpg")
            val cropUri = Uri.fromFile(cropFile)

            val options = UCrop.Options()
            options.withAspectRatio(1f,1f)
            options.withMaxResultSize(1024, 1024)
            options.setToolbarTitle("")
            options.setCircleDimmedLayer(true)
            options.setShowCropFrame(false)
            options.setShowCropGrid(false)
            options.setStatusBarColor(ApplicationContext.getColor(com.sense.kukoo.lib_multistatepage.R.color.white))
            UCrop.of(it.getData()!!, cropUri)
                .withOptions(options)
                .start(this)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        LoggerManager.d(TAG, "requestCode=${requestCode}, resultCode=${resultCode}, data=${data}")
        if (resultCode == RESULT_OK && requestCode == CODE_GET_PHOTO){
            //获取照片成功
            cropPhoto(data)
        }
        if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP){
            data?.let { intent ->
                val resultUri = UCrop.getOutput(intent)
                val headerIcon = File(resultUri?.path!!)
                LoggerManager.d(TAG,"resultUri=${resultUri}")
                LoggerManager.d(TAG,"resultUri.length=${headerIcon.length()}")

                Monet.get(this).load<GlideConfig>(resultUri)
                    .circleCrop()
                    .into(mBinding.ivIcon)

                headerIcon.deleteOnExit()
                mViewModel.setHeaderIcon(headerIcon)
            }
        }
    }

}